/**
 * Created by hsia on 2017/4/27.
 */
var VoiceManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;

}
VoiceManager.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(_this.$parent.find('.search-panel'));
        var functionArray = [
            {fName : 'search_btn', fs : this.findData},
            {fName : 'reset_btn', fs : this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#modelTypeSelect'), parentModelKey:BASIS.MODEL_TYPE.ROOT,change:this.onchangeModel}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.ADVERTISING_CONTENT.ROOT}, this);
        this.initTable();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    initTable : function () {

        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="voice_template_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="voice_template_id" value="${id}" />'
            },
            {
                title : '模板类别',
                field : 'modelTypeName'
            },
            {
                title : '模板内容',
                field : 'unitTypeName'
            },
            {
                title : '默认模板',
                template : '#:Utils.autoReplace(defaultInfo,unitParentKey,unitTypeKey)#'
                /*field : 'defaultInfo'*/
            },
            {
                title : '自定义模板',
                template : '#:Utils.autoReplace(customModel,unitParentKey,unitTypeKey)#'
                /*field : 'customModel'*/
            },
            {
                title : '备注',
                field : 'remark'
            },
            {
                title : '创建人',
                field : 'createUser'
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#voice_template_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnsMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                _this.selectRowId = selected[0];
            }
        });
    },

    findData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#voice_template_data_list').data('kendoGrid');
        var param = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataT = {jsonParam : JSON.stringify(param)};
        var dataSource = _this.sysUtils.getDataSource({url : baseApiPath + 'voice_template/list', data : dataT, dataType : 'odata'});

        grid.setDataSource(dataSource);
    },
    autoReplace:function (oldStr,type) {
        if(type=='SPEECH_TYPE'){
            $(Utils.getModelArrayByParentModelKey(BASIS.MODEL_DATA_TYPE.ROOT)).each(function(index){
                oldStr=oldStr.replace(new RegExp("\\{"+index+"\\}","g"), '['+this.modelName+']');
            });

        }else if(type=='DISPLAY_CONTENT'){
            $(Utils.getModelArrayByParentModelKey(BASIS.DISPLAY_CONTENT.ROOT)).each(function(index){
                if(this.id == type.id && oldStr.indexOf('%s')!=-1){
                    oldStr=oldStr.replaceAll('%s', '['+this.modelName+']');
                    return oldStr;
                }
            });
        }
        return oldStr;
    },
    onchangeModel:function () {
        var _this = this;
        var model = _this.dataItem(this.select());
        voiceManager.autoView(model);
    },
    autoView:function (model) {
        var that = this;
        var ad = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_AD);
        var voice = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_VOICE);
        var display = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_DISPLAY);
        var labname='';
        that.$parent.find('#unitTypeSelect').empty();
        //that.$parent.find('#unittype').show();
        if(model.modelValue == ad){
            labname ='广告内容：';
            Utils.createDataDictDropDownList({div:that.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.ADVERTISING_CONTENT.ROOT}, this);
        }else if(model.modelValue == voice){
            labname ='语音内容：';
            Utils.createDataDictDropDownList({div:that.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.SPEECH_TYPE.ROOT}, this);

        }else if(model.modelValue == display){
            labname ='显示内容：';
            Utils.createDataDictDropDownList({div:that.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.DISPLAY_CONTENT.ROOT}, this);
        }else{
            //that.$parent.find('#unittype').hide();
            return;
        }

        that.$parent.find('#modelLable').html(labname);

    },

    deleteData : function (e) {
        var _this = this;
        if ( !isEmpty(e) ) {
            _this = $(e.target).data('that');
        }
        notification({title : '提示', message : '此操作无法撤销，是否确认删除？'}, 'confirm', {
            callback : function () {
                var ids = '';
                _this.$parent.find('input[type="checkbox"][name="voice_template_id"]:checked').each(function (inx, itm) {
                    ids += $(itm).val() + ',';
                });
                if ( isEmpty(ids) ){
                    notification({title : '提示', message : '请勾选需要删除的数据'}, 'info');
                    return;
                }
                ids = ids.substring(0, ids.length - 1);
                var dataT = { ids : ids };
                JsonpAjax(baseApiPath + 'voice_template/delete', JSON.stringify(dataT), 'json', function (res) {
                    _this.findData();
                }, true);
            }
        });
    },
    openNewWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = false;
        _this.entity = undefined;
        _this.openWindow('新增语音模板');
    },
    openEditWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var id = _this.selectRowId;
        if (isEmpty(id)) {
            notification({title : '提示', message : '请选中需要编辑的数据'}, 'info');
            return;
        }
        _this.isEdit = true;
        JsonpAjax(baseApiPath + 'voice_template/' + id, undefined, 'json', function (res) {
            _this.entity = res;
            _this.openWindow('编辑语音模板');
        }, true);
    },
    openWindow : function (title) {
        this.editDiv = this.sysUtils.openWindow(this.editDiv, {
            title : title,
            width : "630px",
            height : "460px",
            resizable : false,
            content : 'views/parkLotCenter/voice/voice_template_edit.html'
        }, true);
    }
}

var VoiceTemplateEdit = function ( $parent ) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
VoiceTemplateEdit.prototype = {
    init : function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'save_info', fs : this.saveInfo},
            {fName : 'reset_message', fs : this.resetMessage},
            {fName : 'addLabel', fs : this.addLabel},
            {fName : 'cancel', fs : function () { $('#' + voiceManager.editDiv).data('kendoWindow').close(); } }
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        var model = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_AD);
        Utils.createDataDictDropDownList({div:this.$parent.find('#modelTypeSelect'), parentModelKey:BASIS.MODEL_TYPE.ROOT,select:model,change:this.onchangeModel,unshift:true}, this);
        var unit = Utils.getModelValueByModelKey(BASIS.ADVERTISING_CONTENT.ADVERTISING_CONTENT_1);
        Utils.createDataDictDropDownList({div:this.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.ADVERTISING_CONTENT.ROOT,select:unit,change:this.onchangeContent,unshift:true}, this);
        var addModel = Utils.getModelValueByModelKey(BASIS.MODEL_DATA_TYPE.MODEL_DATA_TYPE_0);
        Utils.createDataDictDropDownList({div:this.$parent.find('#infoModel'), parentModelKey:BASIS.MODEL_DATA_TYPE.ROOT,select:addModel,unshift:true}, this);
        this.loadInfo();
    },
    loadInfo : function () {
        if(!voiceManager.isEdit){
            this.$parent.find('#infoTr').hide();
            var unitType = this.$parent.find('#unitTypeSelect').data("kendoDropDownList").dataItem();
            this.sysUtils.mvvmModel.set('defaultInfo',unitType.remark);
            this.sysUtils.mvvmModel.set('customModel',unitType.remark);
            return;
        }
        if (voiceManager.isEdit && !isEmpty(voiceManager.entity) ) {
            if (voiceManager.entity.modelType == Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_VOICE)) {//语音替换
                voiceManager.entity.customModel = this.reback(voiceManager.entity.customModel, 'voice');
                voiceManager.entity.defaultInfo = this.reback(voiceManager.entity.defaultInfo, 'voice');
            } else if (voiceManager.entity.modelType == Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_DISPLAY)) {//显示替换
                voiceManager.entity.customModel = this.reback(voiceManager.entity.customModel, 'display');
                voiceManager.entity.defaultInfo = this.reback(voiceManager.entity.defaultInfo, 'display');
            }
            var model = {};
            model.modelValue = voiceManager.entity.modelType;
            this.autoView(model, voiceManager.isEdit);
            this.sysUtils.setBindFieldValue(voiceManager.entity);
            this.$parent.find("#modelTypeSelect").data("kendoDropDownList").enable(false);
            this.$parent.find("#unitTypeSelect").data("kendoDropDownList").enable(false);
            this.$parent.find('#reset_message').show();
        }
    },
    resetMessage : function (e) {
        var _this = this;
        if ( !isEmpty(e) ) {
            _this = $(e.target).data('that');
        }
        _this.sysUtils.mvvmModel.set('customModel',voiceManager.entity.customModel);
    },
    onchangeModel:function () {
        var _this = this;
        var model = _this.dataItem(this.select());
        voiceTemplateEdit.autoView(model);
    },
    autoView:function (model,bool) {
        var that = this;
        var ad = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_AD);
        var voice = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_VOICE);
        var display = Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_DISPLAY);
        var labname='',unit,unitType,defaultInfo;
        that.$parent.find('#unitTypeSelect').empty();
        if(model.modelValue == ad){
            that.$parent.find('#infoTr').hide();
            labname ='广告类型：';
            unit = Utils.getModelValueByModelKey(BASIS.ADVERTISING_CONTENT.ADVERTISING_CONTENT_1);
            Utils.createDataDictDropDownList({div:this.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.ADVERTISING_CONTENT.ROOT,select:unit,change:that.onchangeContent,unshift:true}, this);
            if(!bool){
                unitType = that.$parent.find('#unitTypeSelect').data("kendoDropDownList").dataItem();
                defaultInfo=unitType.remark;
                that.sysUtils.mvvmModel.set('defaultInfo',defaultInfo);
                that.sysUtils.mvvmModel.set('customModel',defaultInfo);
            }
        }else if(model.modelValue == voice){
            that.$parent.find('#infoTr').show();
            labname ='语音类型：';
            unit = Utils.getModelValueByModelKey(BASIS.SPEECH_TYPE.SPEECH_TYPE_0);
            Utils.createDataDictDropDownList({div:this.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.SPEECH_TYPE.ROOT,select:unit,change:that.onchangeContent,unshift:true}, this);
            if(!bool){
                unitType = that.$parent.find('#unitTypeSelect').data("kendoDropDownList").dataItem();
                defaultInfo=that.autoReplace(unitType.remark,unitType);
                that.sysUtils.mvvmModel.set('defaultInfo',defaultInfo);
                that.sysUtils.mvvmModel.set('customModel',defaultInfo);
            }

        }else if(model.modelValue == display){
            that.$parent.find('#infoTr').hide();
            labname ='显示类型：';
            unit = Utils.getModelValueByModelKey(BASIS.DISPLAY_CONTENT.DISPLAY_CONTENT_0);
            Utils.createDataDictDropDownList({div:this.$parent.find('#unitTypeSelect'), parentModelKey:BASIS.DISPLAY_CONTENT.ROOT,select:unit,change:that.onchangeContent,unshift:true}, this);
            if(!bool){
                unitType = that.$parent.find('#unitTypeSelect').data("kendoDropDownList").dataItem();
                defaultInfo=unitType.remark;
                that.sysUtils.mvvmModel.set('defaultInfo',defaultInfo);
                that.sysUtils.mvvmModel.set('customModel',defaultInfo);
            }
        }
        that.$parent.find('#modelLable').html(labname);

    },
    onchangeContent:function () {
        var _this = this;
        var content = _this.dataItem(this.select());
        var defaultInfo = voiceTemplateEdit.autoReplace(content.remark,content);
        voiceTemplateEdit.sysUtils.mvvmModel.set('defaultInfo',defaultInfo);
        voiceTemplateEdit.sysUtils.mvvmModel.set('customModel',defaultInfo);
    },
    autoReplace:function (oldStr,type) {
        if(type.parentModelKey=='SPEECH_TYPE'){
            $(Utils.getModelArrayByParentModelKey(BASIS.MODEL_DATA_TYPE.ROOT)).each(function(index){
                oldStr=oldStr.replace(new RegExp("\\{"+index+"\\}","g"), '['+this.modelName+']');
            });

        }else if(type.parentModelKey=='DISPLAY_CONTENT'){
            $(Utils.getModelArrayByParentModelKey(BASIS.DISPLAY_CONTENT.ROOT)).each(function(index){
                if(this.id == type.id && oldStr.indexOf('%s')!=-1){
                    oldStr=oldStr.replaceAll('%s', '['+this.modelName+']');
                    return oldStr;
                }
            });
        }
        return oldStr;
    },
    saveInfo : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if ( validityForm(_this.$parent) ){
            var param = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
            var dataT = {entityParam : param};
            var unitTypeSelect = _this.$parent.find('#unitTypeSelect').data("kendoDropDownList").dataItem();
            if(unitTypeSelect){
                param.defaultInfo=unitTypeSelect.remark;
                param.unitTypeKey=unitTypeSelect.modelKey;
            }else{
                param.defaultInfo='';
                param.unitTypeKey='';
            }
            var modelTypeSelect = _this.$parent.find('#modelTypeSelect').data("kendoDropDownList").dataItem();
            if(modelTypeSelect){
                param.modelTypeKey=modelTypeSelect.modelKey;
            }else{
                param.modelTypeKey='';
            }
            param['customModelInfo']=param.customModel;
            if(param.modelType==Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_VOICE)){//语音替换
                param.customModel=_this.changeBack(param.customModel,'voice');
            }else if(param.modelType==Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_DISPLAY)){//显示替换
                param.customModel=_this.changeBack(param.customModel,'display');
            }
            var error = _this.poke(param.customModel);
            if(error.length>0){
                layer.tips('['+error+']格式错误！！！',_this.$parent.find('#customInfo'),{tipsMore: true,tips: [2, '#78BA32']});
                return;
            }

            JsonpAjax(baseApiPath + 'voice_template/save', JSON.stringify(dataT), 'json', function (res) {
                $('#' + voiceManager.editDiv).data('kendoWindow').close();
                voiceManager.isEdit = false;
                voiceManager.findData();
            }, true);
        }
    },
    reback:function (oldStr,type) {//替换字符串中代码块
        if(!isEmpty(oldStr)){
            if('voice'==type){
                $(Utils.getModelArrayByParentModelKey(BASIS.MODEL_DATA_TYPE.ROOT)).each(function(index){
                    oldStr=oldStr.replace(new RegExp("\\{"+index+"\\}","g"), '['+this.modelName+']');
                });
            }else if('display'==type){
                $(Utils.getModelArrayByParentModelKey(BASIS.DISPLAY_CONTENT.ROOT)).each(function(index){
                    if(this.modelValue == voiceManager.entity.unitType && oldStr.indexOf('%s')!=-1){
                        oldStr=oldStr.replaceAll('%s', '['+this.modelName+']');
                        return oldStr;
                    }
                });
            }
        }
        return oldStr;
    },
    changeBack:function(oldStr,type){
        if('voice'==type){
            $(Utils.getModelArrayByParentModelKey(BASIS.MODEL_DATA_TYPE.ROOT)).each(function(index){
                oldStr=oldStr.replaceAll('\\['+this.modelName+'\\]', '{'+index+'}');
            });
        }else if('display'==type){
            $(Utils.getModelArrayByParentModelKey(BASIS.DISPLAY_CONTENT.ROOT)).each(function(index){
                oldStr=oldStr.replaceAll('\\['+this.modelName+'\\]', '%s');
            });
        }
        return oldStr;
    },
    poke:function (str) {//正则去最外层[]
        var i=0;
        var x=0;
        var arr=[];
        var fn=function(s,y,p) {
            var a=fn.arguments,l=a.length,s=a[0],p=a[l-2];
            if(s=="["){i+=1;if(i==1)x=p;}
            if(s=="]"){i-=1;if(i==0)arr.push(str.slice(x+1,p));if(i<0)i=0;}
            return s;
        }
        str.replace(/[\[\]]/g,fn);
        return arr;

    },
    addLabel:function (e) {
        var _this = this;
        if ( !isEmpty(e) ) {
            _this = $(e.target).data('that');
        }
        var oldv=_this.sysUtils.mvvmModel.get('customModel');
        var customChoose = _this.$parent.find('#infoModel').data("kendoDropDownList").dataItem();

        if((oldv+'['+customChoose.modelName+']').length>120){
            layer.tips('语句超出设备支持最大长度,请调整！！！',_this.$parent.find('#customInfo'),{tipsMore: true,tips: [2, '#78BA32']});
        }else{
            _this.sysUtils.mvvmModel.set('customModel',oldv+'['+customChoose.modelName+']');
        }
        /*if(modelType==Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_VOICE)){

        }else if(modelType==Utils.getModelValueByModelKey(BASIS.MODEL_TYPE.MODEL_TYPE_DISPLAY)){

        }*/
    }
}